<template>
  <el-row class="mb-4">
    <el-button @click="query">传输数据</el-button>

    <el-button type="primary" @click="dialogFormVisible1 = true"
      >新增用户</el-button
    >
  </el-row>

  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="uid" label="用户id" width="100"> </el-table-column>
    <el-table-column prop="username" label="用户名" width="100">
    </el-table-column>
    <el-table-column prop="picture" label="用户头像" width="100">
      <template #default="scope">
        <!-- Element-plus -->
        <el-upload
          class="avatar-uploader"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="state.circleUrl" :src="state.circleUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </template>
    </el-table-column>
    <el-table-column prop="biography" label="个人简介"> </el-table-column>
    <!-- <el-table-column prop="password" label="用户密码" width="100">
    </el-table-column> -->
    <el-table-column prop="state" label="用户状态" width="100">
    </el-table-column>
    <el-table-column prop="rid" label="用户角色" width="100"> </el-table-column>
    <el-table-column label="操作" width="220" align="center">
      <template #default="scope">
        <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>

        <el-button
          type="primary"
          @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-button-group>
    <el-button type="primary" :icon="ArrowLeft" @click="previousPage"
      >Previous Page</el-button
    >
    <el-button type="primary" @click="nextPage">
      Next Page<el-icon class="el-icon--right"><ArrowRight /></el-icon>
    </el-button>
  </el-button-group>

  <!-- 增加的对话框 -->
  <el-dialog v-model="dialogFormVisible1" title="增加">
    <el-form :model="form">
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户头像" :label-width="formLabelWidth">
        <el-input v-model="form.avatar2" autocomplete="off" />
      </el-form-item>
      <el-form-item label="个人简介" :label-width="formLabelWidth">
        <el-input v-model="form.biography2" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户密码" :label-width="formLabelWidth">
        <el-input v-model="form.password2" autocomplete="off" />
      </el-form-item>

      <!-- <el-form-item label="用户状态" :label-width="formLabelWidth">
          <el-select v-model="form.state2" placeholder="请选择状态">
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item> -->

      <el-form-item label="用户角色" :label-width="formLabelWidth">
        <el-select v-model="form.rid2" placeholder="请选择角色">
          <el-option label="普通管理员" value="10" />
          <el-option label="超级管理员" value="12" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取消</el-button>
        <el-button type="primar" @click="onSubmit1"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 更新的对话框 -->
  <el-dialog v-model="dialogFormVisible2" title="更新用户">
    <el-form :model="form">
      <!-- <el-form-item label="用户名id" :label-width="formLabelWidth">
          <el-input v-model="form.uid2" autocomplete="off" />
        </el-form-item> -->
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户头像" :label-width="formLabelWidth">
        <el-input v-model="form.avatar2" autocomplete="off" />
      </el-form-item>
      <el-form-item label="个人简介" :label-width="formLabelWidth">
        <el-input v-model="form.biography2" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户密码" :label-width="formLabelWidth">
        <el-input v-model="form.password2" autocomplete="off" />
      </el-form-item>

      <el-form-item label="用户状态" :label-width="formLabelWidth">
        <el-select v-model="form.state2" placeholder="请选择状态">
          <el-option label="正常" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="用户角色" :label-width="formLabelWidth">
        <el-select v-model="form.rid2" placeholder="请选择角色">
          <el-option label="普通管理员" value="10" />
          <el-option label="超级管理员" value="12" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取消</el-button>
        <el-button type="primary" @click="onSubmit2"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<!--  -->

<script lang="ts">
import axios from "axios";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";

import {
  Delete,
  Edit,
  Search,
  Plus,
  ArrowLeft,
  ArrowRight,
} from "@element-plus/icons-vue";

export default {
  data() {
    let key = 1;
    const dialogFormVisible1 = ref(false); //对话框1的显示控制
    const dialogFormVisible2 = ref(false); //对话框2的显示控制
    const formLabelWidth = "140px";
    // const arr = reactive<string[]>([]);
    //  arr.push('Hello');
    var userState = reactive<string[]>([]); //state数组定义,
    var userRid = reactive<string[]>([]); //userid数组定义
    var userName = reactive<string[]>([]); //username数组的定义

    let idx: number = -1;
    var currentPage: number = 1; //
    var pageSize1: number = 2;
    var totalSize: number = 0;

    const state = reactive({
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      sizeList: ["small", "", "large"] as const,
    });

    //对话框的数据
    const form = reactive({
      uid2: "",
      name: "",
      avatar2: "",
      biography2: "",
      password2: "",
      state2: "",
      rid2: "",
    });

    return {
      tableData: [],
      form,
      dialogFormVisible1,
      dialogFormVisible2,
      formLabelWidth,
      key,
      idx,
      userRid,
      userState,
      userName,
      pageSize1,
      currentPage,
      totalSize,
      state,
    };
  },
  methods: {
    //查询的方法
    query() {
      console.log(this.currentPage);

      axios({
        url: "/admin/user/query",
        method: "get",
        params: {
          pageNum: this.currentPage,
          pageSize: 2,
        },
      }).then((res) => {
        for (let index = 0; index < res.data.list.length; index++) {
          //状态数组赋值
          this.userState.push(res.data.list[index].state);
          //rid数组赋值
          this.userRid.push(res.data.list[index].rid);
          //username数组赋值
          this.userName.push(res.data.list[index].username);

          if (res.data.list[index].state == 1) {
            res.data.list[index].state = "正常";
          } else if (res.data.list[index].state == 0) {
            res.data.list[index].state = "禁用";
          }

          if (res.data.list[index].rid == 9) {
            res.data.list[index].rid = "系统管理员";
          } else if (
            res.data.list[index].rid == 10 ||
            res.data.list[index].rid == 11
          ) {
            res.data.list[index].rid = "普通管理员";
          } else if (res.data.list[index].rid == 12) {
            res.data.list[index].rid = "超级管理员";
          }
        }
        this.tableData = res.data.list;
        this.totalSize = res.data.total;
      });
    },

    //  头像上传的方法
    handleAvatarSuccess(response, uploadFile) {
      this.state.circleUrl = URL.createObjectURL(uploadFile.raw);
    },

    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== "image/jpeg") {
        ElMessage.error("Avatar picture must be JPG format!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
      }
      return true;
    },

    //上一页的方法
    previousPage() {
      this.currentPage = this.currentPage - 1;
      if (this.currentPage <= 0) {
        ElMessage("已经是第一页");
        this.currentPage = 1;
      } else {
        this.query();
      }
    },
    //下一页的算法
    nextPage() {
      if (this.totalSize - this.currentPage * this.pageSize1 > 0) {
        this.currentPage = this.currentPage + 1;
        this.query();
      } else {
        ElMessage("已经是最后一页");
      }
    },

    //增加用户的对话框的提交方法
    onSubmit1() {
      // var verifyUsername = this.userName.includes(this.form.name);
      // if (verifyUsername) {
      //   ElMessage("用户名与其他用户重复,请重新输一个");
      // } else {
      this.add();
      this.dialogFormVisible1 = false;
      console.log("submit!");
      console.log(this.form);
      // }
    },
    //更新用户的对话框提交方法
    onSubmit2() {
      this.update();
      this.dialogFormVisible2 = false;
      console.log("submit!");
      // console.log(this.UserData);
    },

    //编辑用户显示这一行的数据
    handleEdit(index: number, row: any) {
      this.idx = index;
      this.key = row.uid;
      this.form.name = row.username;
      // this.form.uid2 = row.uid;
      this.form.avatar2 = row.avatar;
      this.form.biography2 = row.biography;
      this.form.password2 = row.password;
      this.form.state2 = row.state;
      this.form.rid2 = row.rid;
      this.dialogFormVisible2 = true;
    },

    //添加用户的方法
    add() {
      axios({
        url: "/admin/user/saveUser",
        method: "get",
        params: {
          username: this.form.name,
          avatar: this.form.avatar2,
          biography: this.form.biography2,
          password: this.form.password2,
          state: 1, //新增状态默认为正常
          rid: this.form.rid2,
        },
      }).then((res) => {
        this.query();
        console.log("添加是否成功" + res.data);
      });
    },
    //修改用户的方法
    update() {
      // 如果编辑时状态和角色id没变就进入if.
      if (
        this.form.rid2 != "10" &&
        this.form.rid2 != "11" &&
        this.form.rid2 != "12"
      ) {
        this.form.rid2 = this.userRid[this.idx];
      }
      if (this.form.state2 != "1" && this.form.state2 != "0") {
        this.form.state2 = this.userState[this.idx];
      }

      axios({
        url: "/admin/user/updateUser",
        method: "get",
        params: {
          uid: this.key,
          username: this.form.name,
          avatar: this.form.avatar2,
          biography: this.form.biography2,
          password: this.form.password2,
          state: this.form.state2,
          rid: this.form.rid2,
        },
      }).then((res) => {
        this.query();
        console.log("更新是否成功" + res.data);
      });
    },

    handleDelete(index: number, row: any) {
      // 二次确认删除
      ElMessageBox.confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          ElMessage.success("删除成功");
          axios({
            url: "/admin/user/deleteUser",
            method: "get",
            params: {
              uid: row.uid,
            },
          }).then((res) => {
            this.query();
            console.log(row.uid + "删除成功,影响了" + res.data + "行");
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.red {
  color: #f56c6c;
}

.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}
.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>
